#include "guiterm.hpp"

ScrollableTermView::ScrollableTermView(RemoteJob *job, TerminalEmulator *model, CharacterViewConfig *viewConfig, bool abridged)
	:JobViewSegment(job)
{
	this->model = model;
	
	scrollbarVisible = false;
	updatingScrollbar = false;
	
	QSizePolicy sizePolicy(QSizePolicy::Ignored, QSizePolicy::Fixed);
	setSizePolicy(sizePolicy);
	
	layout = new QHBoxLayout();
	layout->setSpacing(0);
	layout->setContentsMargins(0,0,0,0);
	setLayout(layout);
	
	view = new CharacterView(model, viewConfig, abridged);
	layout->addWidget(view);
	setFocusProxy(view);
	
	scrollbar = new QScrollBar(Qt::Vertical);
	scrollbar->setFocusPolicy(Qt::NoFocus);
	scrollbarPlaceholder = new ScrollBarPlaceholder(scrollbar);
	scrollbarPlaceholder->setFocusPolicy(Qt::NoFocus);
	layout->addWidget(scrollbarPlaceholder);
	
	connect(model, SIGNAL(scrollbarChanged(int,int,int)), this, SLOT(scrollbarChanged(int,int,int)));
	connect(scrollbar, SIGNAL(valueChanged(int)), this, SLOT(scrollbarMoved(int)));
}

ScrollableTermView::~ScrollableTermView()
{
	delete layout;
	delete view;
	delete scrollbar;
	delete scrollbarPlaceholder;
}

void ScrollableTermView::finished()
{
	view->finish();
	setFocusProxy(NULL);
	setFocusPolicy(Qt::NoFocus);
	view->setFocusPolicy(Qt::NoFocus);
}

pair<int,int> ScrollableTermView::charsFromPixelSize(pair<int,int> pixelSize, CharacterViewConfig *viewSettings)
{
	// Compute the width of the scrollbar by making a fake one, and cache the
	// result.
	static int scrollbarWidth = -1;
	if(scrollbarWidth < 0) {
		QScrollBar *scrollbar = new QScrollBar();
		scrollbarWidth = scrollbar->sizeHint().width();
		delete scrollbar;
	}
	
	return pair<int,int>(
		(pixelSize.first - scrollbarWidth) / viewSettings->fontWidth,
		pixelSize.second / viewSettings->fontHeight
	);
}

QSize ScrollableTermView::sizeHint() const
{
	return view->sizeHint();
}

//CharacterView *ScrollableTermView::getView()
//	{ return view; }

TerminalEmulator *ScrollableTermView::getModel()
	{ return model; }

void ScrollableTermView::finalizeSize()
{
	view->finalizeSize();
}

void ScrollableTermView::scrollbarChanged(int min, int max, int value)
{
	if(min!=max && !scrollbarVisible) {
		scrollbarVisible = true;
		layout->removeWidget(scrollbarPlaceholder);
		layout->addWidget(scrollbar);
		scrollbar->show();
	}
	updatingScrollbar = true;
	scrollbar->setRange(min, max);
	scrollbar->setValue(value);
	updatingScrollbar = false;
}

void ScrollableTermView::scrollbarMoved(int value)
{
	if(updatingScrollbar) return;
	
	model->setScroll(value);
}

